from types import new_class
from django.core.management import call_command
from rest_framework.test import APITestCase
from common.models import User, Tenant, Role
from common.utils.misc import issue_token_for

TEST_USER = {
    'email': 'zmm@dorabot.com',
    'password': 'password'
}

class ZMMTestCase(APITestCase):
    default_role = 'admin'
    user = None

    @classmethod
    def use_role(cls, role):
        parameterized_cls = new_class('NewZMMTestCase', (cls,))
        parameterized_cls.default_role = role
        return parameterized_cls

    @classmethod
    def setUpTestData(cls):
        # Create the tenant
        schema_name = User.make_default_tenant_schema(TEST_USER['email'])
        tenant = Tenant.objects.create(
            schema_name=schema_name,
            organization='dorabot')

        # Migrate models to the tenant schema
        call_command('tenant_migrate')

        # Create user
        role_create_fun = getattr(Role.objects, f'create_{cls.default_role}_role')
        user_role = role_create_fun(tenant)
        cls.user = User.objects.create(
            email=TEST_USER['email'],
            password=TEST_USER['password'],
            first_name='John',
            last_name='Smith',
            tenant=tenant,
            roles=[user_role]
        )

    def setUp(self):
        access_token = issue_token_for(self.user)['access']
        auth_header = 'Bearer {}'.format(access_token)
        self.client.credentials(
            HTTP_AUTHORIZATION=auth_header)

